package com.example.application.views.store;

import com.example.application.bean.*;
import com.example.application.views.main.MainView;
import com.example.application.views.util.DialogUtil;
import com.example.application.views.util.MyHttpClientUtil;
import com.example.application.views.util.ShowAllInfosUtil;
import com.example.page.PageComponent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.crud.BinderCrudEditor;
import com.vaadin.flow.component.crud.Crud;
import com.vaadin.flow.component.crud.CrudEditor;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.converter.StringToDoubleConverter;
import com.vaadin.flow.data.converter.StringToIntegerConverter;
import com.vaadin.flow.router.Route;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

@Route(value = "supServer", layout = MainView.class)
public class StoServiceView extends Div {
    private User user;

    private Store store;

    private Grid<Service> grid = new Grid<>(Service.class, false);
    private Crud<Service> crud = new Crud<>(Service.class, grid, createPetOwnerEditor());

    private PageBean<Service> pageBean;

    private Service service;

    private TextField name;
    private TextField type;
    private TextField schedule;
    private TextField applicable;
    private TextField serviceSpec;
    private TextField spendTime;
    private TextField clerkLevel;
    private TextField price;

    public StoServiceView(){
        user = (User) UI.getCurrent().getSession().getAttribute("user");
        store = (Store) UI.getCurrent().getSession().getAttribute("store");

        if (user == null){

        }else if(store == null){
            Dialog dialog = new Dialog();
            dialog.setCloseOnEsc(false);
            dialog.setCloseOnOutsideClick(false);
            dialog.removeAll();
            dialog.add(new Text("请先选择门店"));

            Button okBtn = new Button("去选择门店", sure ->{
//           跳转到门店管理界面
                UI.getCurrent().navigate("store");
                dialog.close();
            });

            dialog.add(new Div(okBtn, new Text("      ")));
            dialog.open();
        }else if("门店管理员".equals(user.getIdentity())){
            //在最下面
            this.init();
        }else{
            DialogUtil.adminAuthority();
        }
    }

    public void init(){
        Crud.addEditColumn(grid);
        pageBean = new PageBean<>();
        pageBean.setCurrentPage(1);
        pageBean.setPageSize(3);
        updateForm();

        grid.addColumn(Service::getName).setHeader("名称");
        grid.addColumn(Service::getType).setHeader("种类");
        grid.addColumn(Service::getSchedule).setHeader("排期");
        grid.addColumn(Service::getApplicable).setHeader("适用规格");
        grid.addColumn(Service::getServiceSpec).setHeader("服务规格");
        grid.addColumn(Service::getSpendTime).setHeader("耗时");
        grid.addColumn(Service::getClerkLevel).setHeader("服务等级");
        grid.addColumn(Service::getPrice).setHeader("价格");

        crud.addSaveListener(e->{
            Service s = e.getItem();
            Integer id = s.getId();

            s.setName(name.getValue().trim());
            s.setType(type.getValue().trim());
            s.setPrice(Double.parseDouble(price.getValue().trim()));
            s.setApplicable(applicable.getValue().trim());
            s.setServiceSpec(serviceSpec.getValue().trim());
            s.setClerkLevel(clerkLevel.getValue().trim());
            s.setSchedule(schedule.getValue().trim());
            s.setSpendTime(spendTime.getValue().trim());
            s.setStore(store);

            String url = "";

            if(id == null){
                url = StoServiceURL.SERVICE_ADD;
                s.setStore(store);
            }else{
                url = StoServiceURL.SERVICE_UPDATE;
            }

            try {
                ObjectMapper mapper = new ObjectMapper();
                String msg = MyHttpClientUtil.httpPost(url, s, "utf-8");
                JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, Integer.class);
                ResultBean<Integer> resultBean = mapper.readValue(msg, javaType);

                if(resultBean.getCode() == 0){
                    UI.getCurrent().getPage().executeJs("alert('操作失败');");
                }else{
                    UI.getCurrent().getPage().executeJs("alert('操作成功')");
                }
            } catch (JsonProcessingException jsonProcessingException) {
                jsonProcessingException.printStackTrace();
            }
            updateForm();
        });

        crud.addDeleteListener(e->{
            service = e.getItem();
            if(service != null){
                try {
                    ObjectMapper mapper = new ObjectMapper();
                    String msg = MyHttpClientUtil.httpDelete(StoServiceURL.SERVICE_DELETE, service.getId(), "utf-8");
                    JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, Integer.class);
                    ResultBean<Integer> resultBean = mapper.readValue(msg, javaType);

                    if(resultBean.getCode() == 0){
                        UI.getCurrent().getPage().executeJs("alert('删除失败');");
                    }else{
                        UI.getCurrent().getPage().executeJs("alert('删除成功')");
                    }
                } catch (JsonProcessingException jsonProcessingException) {
                    jsonProcessingException.printStackTrace();
                }
            }
            updateForm();
        });

        PageComponent pageComponent = new PageComponent(pageBean.getCurrentPage(), pageBean.getPageSize(), pageBean.getTolNum(), pageBean.getTolPage()) {
            @Override
            protected void pageNext() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                pageBean.setTolNum(this.tolNum);
                pageBean.setTolPage(this.tolPage);
                updateForm();
            }

            @Override
            protected void pagePrevious() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                pageBean.setTolNum(this.tolNum);
                pageBean.setTolPage(this.tolPage);
                updateForm();
            }

            @Override
            protected void gotoPage() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                pageBean.setTolNum(this.tolNum);
                pageBean.setTolPage(this.tolPage);
                updateForm();
            }

            @Override
            protected void firstPage() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                pageBean.setTolNum(this.tolNum);
                pageBean.setTolPage(this.tolPage);
                updateForm();
            }

            @Override
            protected void lastPage() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                pageBean.setTolNum(this.tolNum);
                pageBean.setTolPage(this.tolPage);
                updateForm();
            }

            @Override
            protected void selectPage() {
                pageBean.setCurrentPage(this.curPage);
                pageBean.setPageSize(this.pageSize);
                pageBean.setTolNum(this.tolNum);
                pageBean.setTolPage(this.tolPage);
                updateForm();
            }
        };

        pageComponent.components.add(crud);
        pageComponent.init();

        this.add(pageComponent);
    }

    private CrudEditor<Service> createPetOwnerEditor() {
        name = new TextField("名称");
        type = new TextField("种类");
        schedule = new TextField("排期");
        applicable = new TextField("适用规格");
        serviceSpec = new TextField("服务规格");
        spendTime = new TextField("耗时");
        clerkLevel = new TextField("服务等级");
        price = new TextField("价格");

        FormLayout form = new FormLayout(name, type, schedule, applicable, serviceSpec, spendTime, clerkLevel, price);
        Binder<Service> binder = new Binder<>(Service.class);
        binder.bind(name, Service::getName, Service::setName);
        binder.bind(type, Service::getType, Service::setType);
        binder.bind(schedule, Service::getSchedule, Service::setSchedule);
        binder.bind(applicable, Service::getApplicable, Service::setApplicable);
        binder.bind(serviceSpec, Service::getServiceSpec, Service::setServiceSpec);
        binder.bind(spendTime, Service::getSpendTime, Service::setSpendTime);
        binder.bind(clerkLevel, Service::getClerkLevel, Service::setClerkLevel);
        binder.forField(price).withConverter(new StringToDoubleConverter("请输入价格")).bind(Service::getPrice, Service::setPrice);

        return new BinderCrudEditor<>(binder, form);
    }

    public void updateForm(){
        try (CloseableHttpClient httpClient = HttpClients.createDefault()){
            ResultBean<PageBean<Service>> resultBean = new ResultBean<>();

            ObjectMapper mapper = new ObjectMapper();

            String url = StoServiceURL.SERVICE_PAGE + "/" + store.getId() + "/" + pageBean.getCurrentPage() + "/" + pageBean.getPageSize();

            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

            String json = EntityUtils.toString(httpResponse.getEntity(), "utf-8");

            JavaType type = mapper.getTypeFactory().constructParametricType(PageBean.class, Service.class);

            JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, type);

            resultBean = mapper.readValue(json, javaType);

            this.pageBean = resultBean.getT();

            grid.setItems(resultBean.getT().getDatas());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
